package com.bestcem.xm.survey.export.type;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.survey.export.BaseTypeHandler;
import com.bestcem.xm.survey.grpc.client.dto.QstructsDto;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

import static com.bestcem.xm.survey.enums.QuestionTypeEnum.QUESTION_TYPE_AUTO_TABLE;

@Component
public class AutoTableHandler implements BaseTypeHandler {

    @Override
    public Map<String, String> getSelectColumnChangeDictV2(JSONObject data, String dtype) {
        Map<String, String> column_change_dict = new HashMap();
        //选项选项
        List<JSONObject> items = (List<JSONObject>) data.getOrDefault("items", Collections.emptyList());
        items.forEach(v -> column_change_dict.put(getSelectRealcolV2(data, v), getSelectReadablecolV2(data, v)));
        return column_change_dict;
    }

    private String getSelectRealcolV2(JSONObject data, JSONObject item) {
        //cid:题目可见编号
        return String.format("%s__%s", data.getString("cid"), item.get("oid"));
    }

    private String getSelectReadablecolV2(JSONObject data, JSONObject item) {
        //cid:题目可见编号
        return String.format("%s__%s", BaseTypeHandler.clearHtml(data.getString("title")), BaseTypeHandler.clearHtml((String) item.getOrDefault("title", "")));
    }

    @Override
    public List<String> getSelectColumnListV2(JSONObject data, String dtype) {
        List<String> column_list = new ArrayList();
        List<JSONObject> items = (List<JSONObject>) data.getOrDefault("items", Collections.emptyList());
        items.forEach(v -> column_list.add(getSelectRealcolV2(data, v)));
        return column_list;
    }

    @Override
    public Map<Object, Object> getSelectAnswerDictV2(JSONObject dataValue, Object answers, String dtype, Boolean score_apply_type) {
        Map<Object, Object> data = new HashMap<>();
        List<JSONObject> items = (List<JSONObject>) dataValue.getOrDefault("items", Collections.emptyList());
        if (CollUtil.isEmpty((Collection) answers)) {
            items.forEach(v -> data.put(getSelectRealcolV2(dataValue, v), 0.0));
        } else {
            items.forEach(item -> {
                Integer gid = item.getInteger("gid");
                long count = ((List<Map>) answers).stream().map(a -> CollUtil.isNotEmpty((List) a.get(gid)) ? ObjectUtil.isNotEmpty(((List) a.get(gid)).get(0)) : false).filter(Boolean::booleanValue).count();
                data.put(getSelectRealcolV2(dataValue, item), Float.valueOf(count));
            });
        }
        return data;
    }

    @Override
    public List<Map<String, Object>> getExtraAnswerDictListV2(JSONObject dataValue, List<Map<String, List<String>>> answers, boolean readablecol) {
        List<Map<String, Object>> data_dict_list = new ArrayList();
        List<JSONObject> items = (List<JSONObject>) dataValue.getOrDefault("items", Collections.emptyList());
        if (CollUtil.isEmpty(answers)) {
            Map<String, Object> data = new LinkedHashMap<>();
            items.forEach(item -> {
                if (readablecol) {
                    data.put(getSelectColV2(dataValue, item), 0.0);
                } else {
                    data.put(getSelectRealcolV2(dataValue, item), 0.0);
                }
            });
            data_dict_list.add(data);
        } else {
            answers.forEach(answer_dict -> {
                Map<String, Object> data = new LinkedHashMap();
                items.forEach(item -> {
                    for (Map.Entry<String, List<String>> entry : answer_dict.entrySet()) {
                        String seq = entry.getKey();
                        List<String> answer = entry.getValue();
                        if (seq.equals(item.getString("seq"))) {
                            if (!readablecol) {
                                data.put(getSelectColV2(dataValue, item), BaseTypeHandler.clearHtml(answer.get(0)));
                            } else {
                                data.put(getSelectReadablecolV2(dataValue, item), BaseTypeHandler.clearHtml(answer.get(0)));
                            }
                            break;
                        } else {
                            if (!readablecol) {
                                data.put(getSelectColV2(dataValue, item), null);
                            } else {
                                data.put(getSelectReadablecolV2(dataValue, item), null);
                            }
                        }
                    }
                });
                data_dict_list.add(data);
            });
        }
        return data_dict_list;
    }

    private String getSelectColV2(JSONObject dataValue, JSONObject item) {
        return String.format("%s__%s", dataValue.getString("cid"), item.getString("oid"));
    }


    @Override
    public List<List<String>> getVarLabelsV2(JSONObject dataValue, boolean not01, boolean need_title) {
        List<List<String>> data = new ArrayList<>();
        List<String> var_list = new ArrayList(), val_list = new ArrayList();
        List<JSONObject> items = (List<JSONObject>) dataValue.getOrDefault("items", Collections.emptyList());
        items.forEach(item ->
                var_list.add(String.format("VARIABLE LABELS %s__%s '%s'.", dataValue.get("cid"), item.get("oid"), getTitles(dataValue, null, item, false))));
        data.add(var_list);
        data.add(val_list);
        return data;
    }

    @Override
    public List<String> getSpssCodeV2(JSONObject param, QstructsDto qstruct) {
        List<JSONObject> items = (List<JSONObject>) param.getOrDefault("items", Collections.emptyList());
        return items.stream().map(item -> String.format("%s__%s", param.get("cid"), item.get("oid"))).collect(Collectors.toList());
    }

    @Override
    public String getQuestionTypeValue() {
        return QUESTION_TYPE_AUTO_TABLE.getValue();
    }
}
